<template>
  <div class="login" :style="'background-image:url(' + Background + ');'">
    <div class="langSelect">
      <span
        :class="$store.state.settings.language == 'zh-CN' ? 'blueText' : ''"
        @click="setLocal('zh-CN')"
        >简</span
      >
      <span>|</span>
      <span
        :class="$store.state.settings.language == 'zh-TW' ? 'blueText' : ''"
        @click="setLocal('zh-TW')"
        >繁</span
      >
      <span>|</span>
      <span
        :class="$store.state.settings.language == 'en-US' ? 'blueText' : ''"
        @click="setLocal('en-US')"
        >EN</span
      >
    </div>
    <div class="login-form">
      <div class="leftImg">
        <img class="leftBg" src="~@/assets/images/login1.png" alt="" />
        <img class="leftimg" :src="Logo" alt="" />
      </div>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        label-position="left"
        label-width="0px"
      >
        <!-- 欢迎登录 -->
        <h3 class="title">{{ $t("login.login1") }}</h3>
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            autocomplete="new-password"
            type="text"
            :placeholder="$t('vip.vip1')"
          >
            <img slot="prefix" src="~@/assets/images/login3.png" alt="" />
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="LookPass ? 'text' : 'password'"
            autocomplete="new-password"
            :placeholder="$t('login.login2')"
            @keyup.enter.native="handleLogin"
          >
            <img slot="prefix" src="~@/assets/images/login4.png" alt="" />
            <img
              slot="suffix"
              v-show="!LookPass"
              src="~@/assets/images/login5.png"
              class="rightEye"
              @click="LookPass = true"
            />
            <img
              slot="suffix"
              v-show="LookPass"
              src="~@/assets/images/login6.png"
              class="rightEye"
              @click="LookPass = false"
            />
          </el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            :placeholder="$t('login.login3')"
            style="width: 50%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="icon-validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" />
          </div>
        </el-form-item>
        <!-- 记住账号 -->
        <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">
          {{ $t("login.login4") }}
        </el-checkbox>
        <el-form-item style="width: 100%">
          <el-button
            class="loginBtn"
            :loading="loading"
            type="primary"
            style="width: 100%"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">{{ $t("login.login5") }}</span>
            <span v-else>{{ $t("login.login6") }}...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <!-- <div v-if="$store.state.settings.showFooter" id="el-login-footer">
      <span v-html="$store.state.settings.footerTxt" />
      <span> ⋅ </span>
      <a href="http://www.beian.miit.gov.cn" target="_blank">{{ $store.state.settings.caseNumber }}</a>
    </div> -->
  </div>
</template>

<script>
import { encrypt } from "@/utils/rsaEncrypt";
import Config from "@/settings";
import { getCodeImg, getLogo } from "@/api/login";
import Cookies from "js-cookie";
import Background from "@/assets/images/login2.png";
import {$icon} from '@/utils/index'

export default {
  name: "Login",
  data() {
    return {
      LookPass: false,
      Background: Background,
      Logo: "",
      codeUrl: "",
      cookiePass: "",
      loginForm: {
        username: "", //LinkCRM
        password: "", //Link123456
        rememberMe: false,
        code: "",
        key: "",
      },
      loginRules: {
        username: [
          // 账号不能为空
          { required: true, trigger: "blur", message: this.$t("login.login7") },
          // 账号最多为10位
          { max: 10, message: this.$t("login.login8"), trigger: "blur" },
        ],
        password: [
          // 密码不能为空
          {
            required: true,
            trigger: "blur",
            message: this.$t("common.common16"),
          },
          // 请输入8~16位字母和数字和字符的密码
          {
            pattern: /^(?!(?:[0-9]+|[a-zA-Z]+|[!-\/:-@\[-`{-~]+)$)[!-~]{8,16}$/,
            message: this.$t("common.common17"),
            trigger: "blur",
          },
        ],
        // 验证码不能为空
        code: [
          { required: true, trigger: "blur", message: this.$t("login.login9") },
        ],
      },
      loading: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // 获取验证码
    this.getCode();
    // 获取LOGO
    this.getLogo();
    // 获取用户名密码等Cookie
    this.getCookie();
    // token 过期提示
    this.point();
  },
  methods: {
    setLocal(val) {
      this.$store.dispatch("settings/changeSetting", {
        key: "language",
        value: val,
      });
      this.$store.dispatch("settings/changeSetting", {
        key: "langTail",
        value: this.langSwitch(val),
      });
      localStorage.setItem("lang", val);
      localStorage.setItem("langTail", this.langSwitch(val));
      location.reload();
    },
    langSwitch(lang) {
      switch (lang) {
        case "zh-CN":
          return "zh";
          break;
        case "en-US":
          return "en";
          break;
        case "zh-TW":
          return "tc";
          break;
        default:
          return "zh";
          break;
      }
    },
    getCode() {
      getCodeImg().then((res) => {
        if (res.code == 10000) {
          this.codeUrl = res.data.base64;
          this.loginForm.key = res.data.key;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getLogo() {
      getLogo().then((res) => {
        if (res.code == 10000) {
          this.Logo = res.data.logo_login;
          if(res.data.terminal_name){
            Config.title = res.data.terminal_name;
            localStorage.setItem("terminal_name",res.data.terminal_name)
            document.title = this.$t('login.login5') + ' - ' + Config.title 
          }
          localStorage.setItem('icon',res.data.open_account_icon)
          $icon()
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      // let password = Cookies.get('password')
      let password = "";
      const rememberMe = Cookies.get("rememberMe");
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? "" : password;
      password = password === undefined ? this.loginForm.password : password;
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: "",
        key: "",
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          key: this.loginForm.key,
        };
        user.password = encrypt(user.password);
        if (valid) {
          this.loading = true;
          if (user.rememberMe) {
            Cookies.set("username", user.username, {
              expires: Config.passCookieExpires,
            });
            // Cookies.set('password', user.password, { expires: Config.passCookieExpires })
            Cookies.set("rememberMe", user.rememberMe, {
              expires: Config.passCookieExpires,
            });
          } else {
            Cookies.remove("username");
            // Cookies.remove('password')
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", user)
            .then((res) => {
              this.loading = false;
              if (res.code == 10000) {
                // this.$router.push({ path: this.redirect || "/" });
                this.$router.push({ path: "/" });
              } else {
                this.getCode();
                this.loginForm.code = "";
              }
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
              this.loginForm.code = "";
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    point() {
      const point = Cookies.get("point") !== undefined;
      if (point) {
        // 当前登录状态已过期，请重新登录！
        this.$notify({
          title: this.$t("common.common5"),
          message: this.$t("login.login10"),
          type: "warning",
          duration: 5000,
        });
        Cookies.remove("point");
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
  position: relative;
}
.langSelect {
  position: absolute;
  top: 20px;
  right: 30px;
  cursor: pointer;
  user-select: none;
}
.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
  font-weight: 500;
  letter-spacing: 3px;
  font-size: 22px;
}

.login-form {
  background: #ffffff;
  width: 800px;
  height: 500px;
  overflow: hidden;
  box-shadow: 0px 4px 33px 4px rgba(240, 240, 240, 0.8);
  display: flex;
  align-items: center;

  .leftImg {
    position: relative;
    width: 350px;
    font-size: 0;
    .leftBg {
      width: 100%;
    }
    .leftimg {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-width: 204px;
    }
  }
  .el-form {
    flex: 1;
    padding: 0 50px;
  }
  .loginBtn {
    font-size: 16px;
    padding: 11px;
  }
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
    .el-input__prefix,
    .el-input__suffix-inner {
      img {
        width: 20px;
        height: 20px;
        vertical-align: middle;
      }
      .rightEye {
        cursor: pointer;
        user-select: none;
      }
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 49%;
  display: inline-block;
  height: 38px;
  float: right;
  img {
    width: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
